package com._520it.day2._06_template;

import java.beans.BeanInfo;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.sql.ResultSet;
import java.sql.SQLException;

import com._520it.day2._06_template.crud.Student;

//单个对象的结果及处理器，一行数据封装成一个对象
public class BeanHandler<T> implements IResultSetHandler<T>{

	private Class<T> clazz=null;
	
	
	public BeanHandler(Class<T> clazz) {
		super();
		this.clazz = clazz;
	}


	@Override
	public T handle(ResultSet rs) throws SQLException {
		
		try {
			T obj = clazz.newInstance();
			//得到某一份字节中所有的信息（方法/属性/事件）
			BeanInfo beanInfo = Introspector.getBeanInfo(clazz,Object.class);
			//获取该对象中所有的属性
			PropertyDescriptor[] pds = beanInfo.getPropertyDescriptors();
			if (rs.next()) {
				for (PropertyDescriptor pd : pds) {
					String columnName = pd.getName();
					Object value = rs.getObject(columnName);
					
					//调用该属性对象的setter方法
					pd.getWriteMethod().invoke(obj, value);
				}
			}
			return obj;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static void main(String[] args) {
		String sql="SELECT * FROM t_student WHERE id=?";
		Student stu = JDBCTemplate.query(sql, new BeanHandler<>(Student.class),8L);
		System.out.println(stu);
		System.out.println("-----------------------");
		sql="SELECT * FROM productdir WHERE id=?";
		ProductDir dir = JDBCTemplate.query(sql, new BeanHandler<>(ProductDir.class), 3L);
		System.out.println(dir);
	}
}
